function returnFamilyAttribute(value,index,field){
    return value?"<input type='text' name='familyInformations["+index+"]."+field+"' value='"+value+"'>"
        :"<input type='text' name='familyInformations["+index+"]."+field+"' value=''>";
}
function returnWorkAttribute(value,index,field){
    return value?"<input type='text' name='workInformations["+index+"]."+field+"' value='"+value+"'>"
        :"<input type='text' name='workInformations["+index+"]."+field+"' value=''>";
}

$(function () {
    var employee_datagrid = $("#employee_datagrid");
    var emp_dialog = $("#emp_dialog");
    var emp_form = $("#emp_form");

    var detailInfo_dialog = $("#detailInfo_dialog");
    var detailInfo_form = $("#detailInfo_form");

    var home_datagrid = $("#home_datagrid");
    var work_datagrid = $("#work_datagrid");


    employee_datagrid.datagrid({
        url: '/employee/query.do',
        fit: true,
        fitColumns: true,
        columns: [[
            {field: 'state', hidden:true},
            {field: 'admin',hidden:true},
            {field: 'roles', hidden:true},
            {field: 'username', title: '用户名', width: 100},
            {field: 'realname', title: '真实姓名', width: 100},
            {field: 'tel', title: '电话号码', width: 100},
            {field: 'email', title: '邮箱', width: 100},
            {
                field: 'dept', title: '部门', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {field: 'hireDate', title: '入职时间', width: 100, sortable: true},
            {
                field: 'state', title: '状态', width: 100, formatter: function (value) {
                return value ? "在职" : "<font color='red'>离职</font>"
            }
            },
        ]],
        singleSelect: true,
        pagination: true,
        toolbar: "#emp_btns",
        sortName: 'hireDate',
        sortOrder: 'desc',
        onClickRow: function (index, row) {
            if (row.state) {
                $("#changeState_btn").linkbutton({
                    text: '离职'
                })
            } else {
                $("#changeState_btn").linkbutton({
                    text: '复职'
                })
            }
        }
    });
    home_datagrid.datagrid({
        url: '/familyInformation/selectByEmployeeId.do',
        fit: true,
        fitColumns: true,
        columns: [[
            {field:'id',hidden:true,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'id');
            }},
            {field: 'family', title: '家属', width: 100,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'family');
            }},
            {field: 'familyName', title: '家人姓名', width: 100,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'familyName');
            }},
            {field: 'company', title: '公司', width: 100,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'company');
            }},
            {field: 'job', title: '工作', width: 100,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'job');
            }},
            {field: 'tel', title: '联系电话', width: 100,formatter:function(value,row,index){
                return returnFamilyAttribute(value,index,'tel');
            }}
        ]],
        toolbar:"#home_btns",
        singleSelect: true,
        pagination: true
    });
    work_datagrid.datagrid({
        url: '/workInformation/selectByEmployeeId.do',
        fit: true,
        fitColumns: true,
        columns: [[
            {field:'id',hidden:true,formatter:function(value,row,index){
                return returnWorkAttribute(value,index,'id');
            }},
            {field: 'work', title: '工作', width: 100,formatter:function(value,row,index){
                return returnWorkAttribute(value,index,'work');
            }},
            {field: 'role', title: '职务', width: 100,formatter:function(value,row,index){
                return returnWorkAttribute(value,index,'role');
            }},
            {field: 'beginDate', title: '开始时间', width: 100,formatter:function(value,row,index){
                return value?"<input type='date' name='workInformations["+index+"].beginDate' value='"+value+"'>"
                    :"<input type='date' name='workInformations["+index+"].beginDate' value=''>";
            }},
            {field: 'endDate', title: '结束时间', width: 100,formatter:function(value,row,index){
                return value?"<input type='date' name='workInformations["+index+"].endDate' value='"+value+"'>"
                    :"<input type='date' name='workInformations["+index+"].endDate' value=''>";
            }},
            {field: 'detail', title: '详情', width: 100,formatter:function(value,row,index){
                return returnWorkAttribute(value,index,'detail');
            }}
        ]],
        toolbar:"#work_btns",
        singleSelect: true,
        pagination: true
    });
    emp_dialog.dialog({
        width: 300,
        height: 400,
        buttons: "#save_btns",
        closed: true,
        onClose: function () {
            emp_form.form('clear');
            employee_datagrid.datagrid('reload',{});
        }
    });
    $("#import_dialog").dialog({
        title: '文件上传',
        width: 200,
        height: 200,
        closed: true,
        buttons: '#import_btns',
        onClose: function () {
            $("#import_form").form('clear');
        }
    });
    $("#reset_password").dialog({
        width: 300,
        height: 200,
        buttons: "#password_btns",
        closed: true,
    });

    detailInfo_dialog.dialog({
        width: 700,
        height: 500,
        buttons: "#saveDetail_btns",
        closed: true,
        onClose: function () {
            detailInfo_form.form('clear');
            employee_datagrid.datagrid('reload',{});
            home_datagrid.datagrid('reload',{});
            work_datagrid.datagrid('reload',{});
        }
    });


    $("a[data-cmd]").click(function () {
        var methodName = $(this).data('cmd');
        methodObject[methodName]();
    });


    var methodObject = {
        add: function () {
            $("#password_tr").show();
            emp_dialog.dialog('setTitle', '新增员工');
            emp_dialog.dialog('open');
        },
        edit: function () {
            $("#password_tr").hide();
            var row = employee_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', "请选中一条数据", 'warning');
                return;
            }
            //回显角色数据
            $.get('/employee/getRoleByEmployeeId.do', {employeeId: row.id}, function (data) {
                $("#role_combobox").combobox('setValues', data);
            })
            row['dept.id'] = row.dept.id;
            emp_form.form('load', row
            );
            emp_dialog.dialog('setTitle', '编辑员工');
            emp_dialog.dialog('open');
        },
        changeState: function () {
            var row = employee_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', "请选中一条数据", 'warning');
                return;
            }
            $.messager.confirm('确认对话框', '您确定执行该操作吗？', function (r) {
                if (r) {
                    $.get("/employee/changeState.do", {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', '操作成功', 'info')
                            employee_datagrid.datagrid('reload');
                        } else {
                            $.messager.alert('温馨提示', data.msg, 'warning');
                        }
                    })
                }
            });
        },
        reload: function () {
            employee_datagrid.datagrid('reload');
        },
        save: function () {
            emp_form.form('submit', {
                url: '/employee/saveOrUpdate.do',
                onSubmit: function (param) {
                    var ids = $("#role_combobox").combobox('getValues');
                    for (var i = 0; i < ids.length; i++) {
                        param['roles[' + i + '].id'] = ids[i];
                    }
                },
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert('温馨提示', '保存成功', 'info');
                        methodObject.cancel();
                        employee_datagrid.datagrid('reload');
                    } else {
                        $.messager.alert('温馨提示', data.msg, 'error');
                    }
                }
            })
        },
        cancel: function () {
            emp_dialog.dialog('close');
        },
        cancel2: function () {
            $("#reset_password").dialog('close');
        },
        query: function () {
            var keyword = $("[name=keyword]").val();
            var deptId = $("[name=deptId]").val();
            employee_datagrid.datagrid('load', {
                keyword: keyword,
                deptId: deptId
            })
        },
        openPassword: function () {
            $("#reset_password").dialog('setTitle', '重置密码');
            var row = employee_datagrid.datagrid('getSelected');
            if (!row) {
                $.messager.alert('温馨提示', "请选中一条数据", 'warning');
                return;
            }
            $("#password_form").form('load', row);
            $("#reset_password").dialog('open')
        },
        resetPassword: function () {
            $("#password_form").form('submit', {
                url: '/employee/resetPassword.do',
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert('温馨提示', '操作成功', 'info');
                        methodObject.cancel2();
                        employee_datagrid.datagrid('reload');
                    } else {
                        $.messager.alert('温馨提示', data.msg, 'error');
                    }
                }
            })
        },
        exportXls: function () {
            var keyword = $("[name=keyword]").val();
            window.location.href = '/employee/exportXls.do?keyword=' + keyword;
        },
        import: function () {
            $("#import_dialog").dialog('open');
        },
        import_save: function () {
            $("#import_form").form('submit', {
                url: '/employee/importXls.do',
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert('温馨提示', '上传成功', 'info');
                        methodObject.import_cancel();
                    } else {
                        $.messager.alert('温馨提示', data.msg, 'error');
                    }
                }
            })
        },
        import_cancel: function () {
            $("#import_dialog").dialog('close');
        },

        saveDetail: function () {
            detailInfo_form.form('submit', {
                url: '/employee/saveOrUpdate.do',
                onSubmit: function (param) {
                    var familyInformations = home_datagrid.datagrid("getRows");
                    console.log(familyInformations);

                     var ids = $("#detail_role_combobox").combobox('getValues');
                 for (var i = 0; i < ids.length; i++) {
                 param['roles[' + i + '].id'] = ids[i];
                 }
                 },
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert('温馨提示', '保存成功', 'info');
                        methodObject.cancelDetail();
                        employee_datagrid.datagrid('reload',{});
                        home_datagrid.datagrid('reload',{});
                        work_datagrid.datagrid('reload',{});
                    } else {
                        $.messager.alert('温馨提示', data.msg, 'error');
                    }
                }
            })
        },

        cancelDetail: function () {
            detailInfo_dialog.dialog('close');
        },

        addHome:function(){
            home_datagrid.datagrid('appendRow',{});
        },
        delHome:function(){
            var row = home_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', "快选一条数据删除!", 'warning');
                return;
            }

            var index = home_datagrid.datagrid("getRowIndex",row);
            home_datagrid.datagrid("deleteRow",index);

        },
        addWork:function(){
            work_datagrid.datagrid('appendRow',{});
        },
        deWork:function(){
            var row = work_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', "快选一条数据删除!", 'warning');
                return;
            }

            var index = work_datagrid.datagrid("getRowIndex",row);
            work_datagrid.datagrid("deleteRow",index);

        },

        detail: function () {
            var row = employee_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', "快选一条数据!", 'warning');
                return;
            }
            console.log(row);

            //回显数据
            $.get('/employee/getRoleByEmployeeId.do', {employeeId: row.id}, function (data) {
                $("#detail_role_combobox").combobox('setValues', data);
            });
            row['employeeId']=row.id;
            row['dept.id'] = row.dept.id;
            if(row.detailInformation !=null){
                row['detailInformation.id']=row.detailInformation.id;
                row['detailInformation.gender']=row.detailInformation.gender;
                row['detailInformation.hireType']=row.detailInformation.hireType;
                row['detailInformation.nation']=row.detailInformation.nation;
                row['detailInformation.identityCardNumber']=row.detailInformation.identityCardNumber;
                row['detailInformation.politicsStatus']=row.detailInformation.politicsStatus;
                row['detailInformation.education']=row.detailInformation.education;
                $("#birthday_datebox").datebox("setValue",'row.detailInformation.birthday');
                row['detailInformation.nativePlace']=row.detailInformation.nativePlace;
                row['detailInformation.workingYears']=row.detailInformation.workingYears;
                row['detailInformation.residenceType']=row.detailInformation.residenceType;
                row['detailInformation.bankAccountType']=row.detailInformation.bankAccountType;
                row['detailInformation.remark']=row.detailInformation.remark;
                row['detailInformation.bankAccount']=row.detailInformation.bankAccount;
                row['detailInformation.basePay']=row.detailInformation.basePay;
                row['detailInformation.medicalInsurance']=row.detailInformation.medicalInsurance;
                row['detailInformation.birthInsurance']=row.detailInformation.birthInsurance;
                row['detailInformation.endowmentInsurance']=row.detailInformation.endowmentInsurance;
                row['detailInformation.accumulationFund']=row.detailInformation.accumulationFund;
            }

             home_datagrid.datagrid("load",{empId:row.id});
            if(row.familyInformations !=null){
               $.each(row.familyInformations,function (i,familyInformation) {
                    row['familyInformations['+i+'].id']=familyInformation.id;
                    row['familyInformations['+i+'].employeeId']=familyInformation.employeeId;
                    row['familyInformations['+i+'].family']=familyInformation.family;
                    row['familyInformations['+i+'].familyName']=familyInformation.familyName;
                    row['familyInformations['+i+'].company']=familyInformation.company;
                    row['familyInformations['+i+'].job']=familyInformation.job;
                    row['familyInformations['+i+'].tel']=familyInformation.tel;
               });
            }
             work_datagrid.datagrid("load",{empId:row.id});

            if(row.workInformations !=null){
                $.each(row.workInformations,function (i,workInformation) {
                    row['workInformations['+i+'].id']=workInformation.id;
                    row['workInformations['+i+'].work']=workInformation.work;
                    row['workInformations['+i+'].role']=workInformation.role;
                    row['workInformations['+i+'].beginDate']=workInformation.beginDate;
                    row['workInformations['+i+'].endDate']=workInformation.endDate;
                    row['workInformations['+i+'].detail']=workInformation.detail;
                });

            }

            detailInfo_form.form("load", row);

            console.log(row.id);
            detailInfo_dialog.dialog('setTitle', '详细信息');
            detailInfo_dialog.dialog('open');
        }
    }
})


